import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_lqy_demo/common/event/http_error_event.dart';
import 'package:flutter_lqy_demo/common/event/index.dart';
import 'package:flutter_lqy_demo/common/net/code.dart';
import 'package:flutter_lqy_demo/common/style/gsy_style.dart';
import 'package:flutter_lqy_demo/page/home/home_page.dart';
import 'package:flutter_lqy_demo/page/me/my_page.dart';
import 'package:flutter_lqy_demo/page/welcome/welcome_page.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'common/utils/navigator_utils.dart';

class FlutterReduxApp extends StatefulWidget {
  const FlutterReduxApp({super.key});

  @override
  _FlutterReduxAppState createState() => _FlutterReduxAppState();
}

class _FlutterReduxAppState extends State<FlutterReduxApp>
    with HttpErrorListener {
  NavigatorObserver navigatorObserver = NavigatorObserver();
  String localCode = 'en';

  @override
  void initState() {
    super.initState();
    // Future.delayed(const Duration(seconds: 0), () {
    /// 通过 with NavigatorObserver ，在这里可以获取可以往上获取到
    /// MaterialApp 和 StoreProvider 的 context
    /// 还可以获取到 navigator;
    /// 比如在这里增加一个监听，如果 token 失效就退回登陆页。
    //   navigatorObserver.navigator!.context;
    //   navigatorObserver.navigator;
    // });
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
        designSize: const Size(360, 690),
        minTextAdapt: true,
        splitScreenMode: true,
        // builder: (_, child) {
        //   return MaterialApp(
        //     debugShowCheckedModeBanner: false,
        //     // title: 'First Method',
        //     // You can use the library anywhere in the app even in theme
        //     theme: ThemeData(
        //       primarySwatch: Colors.blueGrey,
        //       textTheme: Typography.englishLike2018.apply(fontSizeFactor: 1.sp),
        //     ),
        //     home: child,
        //   );
        // },
        child: GetMaterialApp(
            navigatorKey: navKey,

            ///多语言实现代理
            localizationsDelegates: const [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            supportedLocales: const [
              Locale('zh'),
              Locale('en'),
            ],
            locale: Locale(localCode),
            // theme: store.state.themeData,
            navigatorObservers: [navigatorObserver],

            ///命名式路由
            /// "/" 和 MaterialApp 的 home 参数一个效果
            ///⚠️ 这里的 name调用，里面 pageContainer 方法有一个 MediaQuery.of(context).copyWith(textScaleFactor: 1),
            ///⚠️ 而这里的 context 用的是 WidgetBuilder 的 context  ～
            ///⚠️ 所以 MediaQuery.of(context) 这个 InheritedWidget 就把这个 context “登记”到了 Element 的内部静态 _map 里。
            ///⚠️ 所以键盘弹出来的时候，触发了顶层的 MediaQueryData 发生变化，自然就触发了“登记”过的 context 的变化
            ///⚠️ 比如 LoginPage 、HomePage ····
            ///⚠️ 所以比如你在 搜索页面 键盘弹出时，下面的 HomePage.sName 对应的 WidgetBuilder 会被触发
            ///⚠️ 这个是我故意的，如果不需要，可以去掉 pageContainer 或者不要用这里的 context
            routes: {
              WelcomePage.sName: (context) {
                return const WelcomePage();
              },
              HomePage.sName: (context) {
                return NavigatorUtils.pageContainer(const HomePage(), context);
              },

              MePage.sName: (context) {
                return NavigatorUtils.pageContainer(const MePage(), context);
              },
              // LoginPage.sName: (context) {
              //   return NavigatorUtils.pageContainer(const LoginPage(), context);
              // },

              // ///使用 ModalRoute.of(context).settings.arguments; 获取参数
              // PhotoViewPage.sName: (context) {
              //   return const PhotoViewPage();
              // },
              // "/": (context) {
              //   return NavigatorUtils.pageContainer(
              //       const MyHomePage(title: "Flutter"), context);
              // },
            }));
  }
}

mixin HttpErrorListener on State<FlutterReduxApp> {
  StreamSubscription? stream;

  GlobalKey<NavigatorState> navKey = GlobalKey();

  @override
  void initState() {
    super.initState();

    ///Stream演示event bus
    stream = eventBus.on<HttpErrorEvent>().listen((event) {
      errorHandleFunction(event.code, event.message);
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (stream != null) {
      stream!.cancel();
      stream = null;
    }
  }

  ///网络错误提醒
  errorHandleFunction(int? code, message) {
    var context = navKey.currentContext!;
    switch (code) {
      case Code.NETWORK_ERROR:
        showToast("network_error".tr);
        break;
      case 401:
        showToast("network_error_401".tr);
        break;
      case 403:
        showToast("network_error_403".tr);
        break;
      case 404:
        showToast("network_error_404".tr);
        break;
      case 422:
        showToast("network_error_422".tr);
        break;
      case Code.NETWORK_TIMEOUT:
        //超时
        showToast("network_error_timeout".tr);
        break;

      default:
        showToast("${"network_error_unknown".tr}$message");
        break;
    }
  }

  showToast(String message) {
    Fluttertoast.showToast(
        msg: message,
        gravity: ToastGravity.CENTER,
        toastLength: Toast.LENGTH_LONG);
  }
}
